﻿/**
 * Migre.me API
 * 
 * For more info go to: 
 * http://migre.me/blog/api-gerador-de-urls/
 * 
 * Or
 * http://code.google.com/p/migreme-as3/
 * 
 * @author	Lucas Araujo <araujo.lucas [at] gmail.com> - http://twitter.com/LucasAraujo
 */
package migreme.api
{
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	
	import migreme.api.events.MigremeEvent;
	
	/**
	 * 
	 */
	public class Migreme extends EventDispatcher
	{
		/**
		 * 
		 */
		protected var MigremeAPIURL:String = 'http://migre.me/api.xml?url=';
		
		/**
		 * 
		 */
		protected var loader:URLLoader;

		/**
		 * 
		 */
		public var lastURL:String;
		
		/**
		 * 
		 */		
		public function Migreme():void
		{
		}
		
		/* 
		 * Shorten
		 * 
		 * @param	url
		 */
		public function shorten(url:String):void
		{
			if (this.loader == null)
			{
				this.loader = new URLLoader();
				this.loader.addEventListener(Event.COMPLETE, completeHandler);
				this.loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				this.loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
				
			}
			url = this.MigremeAPIURL + encodeURIComponent(url);
			this.lastURL = url;
			var request:URLRequest = new URLRequest(url);
			this.loader.load(request);
		}
		
		/**
		 * Complete Handler
		 * 
		 * @param	event
		 */
		protected function completeHandler(event:Event):void
		{
			var result:MigremeEvent = new MigremeEvent(MigremeEvent.ON_URL_SHORTED);
			var xml:XML = new XML(this.loader.data);
			var data:Object = new Object();
            for each (var tempXML:XML in xml.children())
			{
				data[tempXML.name()] = tempXML;
			}
			result.data = data;
			this.dispatchEvent(result);
		}

		/**
		 * Error Handler
		 * 
		 * @param	errorEvent
		 */
		protected function errorHandler(errorEvent:IOErrorEvent):void
		{
			var t:MigremeEvent = new MigremeEvent(MigremeEvent.ON_ERROR);
			t.data = errorEvent.text;
			this.dispatchEvent(t);
		}
	}
}